package ru.hh.team02.chat.client;

import java.io.IOException;
import java.net.Socket;

import ru.hh.team02.chat.server.ChatServer;
import ru.hh.team02.chat.utils.StringSocket;

/*
 * task, which hangs on client socket and listens to it
 */
public class Client implements Runnable {
    private StringSocket socket;

    private String name = "";

    public Client(Socket socket) {
        this.socket = new StringSocket(socket);
    }

    public String getName() {
        return name;
    }

    public String getRoom() {
        return ChatServer.registry.getClientRoom(getName());
    }

    @Override
    public void run() {
        try {
            socket.write("connected");
            System.out.println("Client has connected.");

            registerClient();

            String message = "";
            do {
                message = socket.read();
                handleMessage(message);
            } while (!message.equals("exit"));
        } catch (IOException e) {
            System.out.println("client went down");
        } finally {
            ChatServer.registry.deleteClient(this);
            socket.close();
        }
    }

    /*
     * change current room to newRoom
     */
    // void changeRoom(String newRoom) {
    // ChatServer.registry.changeRoom(this, newRoom);
    // room = newRoom;
    // }

    /*
     * sends message to client
     */
    public void sendMessageToClientComputer(String message) {
        try {
            socket.write(message);
        } catch (IOException e) {

        }
    }

    /*
     * puts message in the queue. in current version one message per client (not
     * per room)
     */
    private void handleMessage(String message) {
        System.out.println(message);

        if (message.startsWith("change")) {
            String[] info = message.split(" ");
            if (info.length == 2) {
                ChatServer.registry.changeRoom(this, info[1]);
            }
        } else {
            ChatServer.messanger.sendMessageToRoom(name + "> " + message,
                    getRoom());
        }
    }

    // ------------------------------------------ AUTHENTIFICATION METHODS

    private void registerClient() throws IOException {
        String room;
        do {
            socket.write("Available rooms: " + ChatServer.registry.getRoomNames().toString()
                         + ". Input room name:");
            room = socket.read();
        } while (!ChatServer.registry.hasRoom(room));
        socket.write("Ok");
        do {
            socket.write("Input login");

            // At this point the client is not registered anywhere
            // and won't be accessed by anybody.
            // So it's OK to have their name not matching the
            // client registry.
            this.name = socket.read();
        } while (this.name.length() > 0
                && !ChatServer.registry.addClient(this, room));
        socket.write("Ok");
    }

}
